package com.atguigu.gmall.product.service.impl;

import com.atguigu.gmall.common.config.minio.properties.AppMinioProperties;
import com.atguigu.gmall.common.util.DateUtil;
import com.atguigu.gmall.product.service.FileUploadService;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Date;
import java.util.UUID;

@Data
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    AppMinioProperties minioProperties;
    @Autowired
    MinioClient minioClient;

    @Override
    public String uploadToMinio(MultipartFile file) throws Exception{



//        1、创建一个 MinioClient
//        MinioClient minioClient = new MinioClient(
//                "http://192.168.200.100:9000/",
//                "admin",
//                "admin123456");
//
//        //2判断桶是否存在
//        //2、检查存储桶是否已经存在
//        if(!minioClient.bucketExists("mall")){
//            minioClient.makeBucket("mall");
//            minioClient.setBucketPolicy("mall",policy);
//        }

        if (!minioClient.bucketExists(minioProperties.getBucket())){
            minioClient.makeBucket(minioProperties.getBucket());
        }

        //3 上传文件
        String date = DateUtil.formatDate(new Date());

        String objectName = date + "/" + UUID.randomUUID().toString().replace("-","")
                + "-"
                + file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();

        //参数
        PutObjectOptions options = new PutObjectOptions(inputStream.available(), -1L);
        options.setContentType(file.getContentType());

        //4返回文件的访问地址
        String url = minioProperties.getEndpoint() + "/" + minioProperties.getBucket() + "/" + objectName;
        return url;
    }
}
